package password.hb.com.password.model;

import android.util.Log;

import com.activeandroid.query.Select;
import java.util.ArrayList;
import java.util.List;

import password.hb.com.password.entity.Password;
import password.hb.com.password.factory.ThreadFactory;

/**
 * Created by A on 2016/12/6.
 */

public class PasswordModel {

    private static PasswordModel model;

    private List<Password> mCache;//password缓存

    private PasswordModel(){
//        mCache = new ArrayList<>();
        getAllPassword();
    }

    public static PasswordModel getInstance(){
        if(model == null){
            synchronized (PasswordModel.class) {
                if(model == null) {
                    model = new PasswordModel();
                }
            }
        }
        return model;
    }

    //获取所有的密码
    public List<Password> getAllPassword(){
        if(mCache==null || mCache.size()==0){
            mCache = new Select().from(Password.class).execute();
        }
        return mCache;
    }

    public Password getByIndex(int index){
        if(index<0 || index>mCache.size()){
            return null;
        }else{
            return mCache.get(index);
        }
    }

    //保存
    public void save(final Password pwd){
        for(Password p : mCache){
            if(p.isSameModel(pwd)){
                final Password deleteP = p;
                mCache.remove(p);
                ThreadFactory.getNormalPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        deleteP.delete();
                    }
                });
                break;
            }
        }
        mCache.add(pwd);
        ThreadFactory.getNormalPool().execute(new Runnable() {
            @Override
            public void run() {
                pwd.save();
            }
        });
    }


    //删除
    public void delete(final Password pwd){
        Password password1 = null;
        for(Password p : mCache){
            if(p.isSameModel(pwd)){
                password1 = p;
                break;
            }
        }
        if(password1!=null){
            mCache.remove(pwd);
            ThreadFactory.getNormalPool().execute(new Runnable() {
                @Override
                public void run() {
                    pwd.delete();
                }
            });
        }

    }

    //修改
//    public void update(final Password pwd){
//        Password password1 = null;
//        for(Password p : mCache){
//            if(p.isSameModel(pwd)){
//                password1 = p;
//                break;
//            }
//        }
//        if(password1!=null){
//            mCache.remove(password1);
//            mCache.add(pwd);
//            ThreadFactory.getNormalPool().execute(new Runnable() {
//                @Override
//                public void run() {
//                    pwd.save();
//                }
//            });
//        }
//    }

}
